package cn.itsource.org.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.server.HttpServerRequest;
import cn.itsource.basic.config.exception.BusinessException;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.JsonResult;
import cn.itsource.basic.util.RedisService;
import cn.itsource.basic.util.SendMessageService;
import cn.itsource.org.domain.User;
import cn.itsource.org.mapper.UserMapper;
import cn.itsource.org.pojo.Do.LoginDo;
import cn.itsource.org.pojo.loginInfo.LoginInfo;

import cn.itsource.org.pojo.vo.LoginVo;
import cn.itsource.org.query.UserQuery;
import cn.itsource.org.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class UserServiceImpl extends BaseServiceImpl<User, UserQuery> implements IUserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private SendMessageService messageService;
    @Resource
    private RedisService redisService;
    @Override
    public void verifyPhone(String phone) {
        /*String regex = "^((13[0-9])|(14[579])|(15([0-3]|[5-9]))|(16[56])|(17[0-8])|(18[0-9])|(19[1589]))\\d{8}$";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(phone);
        //验证手机
        boolean matches = m.matches();*/
        //hutooL工具类
        boolean matches = Validator.isMobile(phone);
        if(!matches){
            throw  new BusinessException("手机号格式有误");
        }
        //验证手机号
        User users = userMapper.selectPhone(phone);
        if(users!=null){
            throw  new BusinessException("手机号已经注册");
        }
    }

    @Override
    public void verifyCode(String phone,HttpServerRequest request) {
        //发送短信验证码
        String verify = RandomUtil.randomNumbers(4);
      //  messageService.sendMessage(phone,verify);
        Integer integer = Integer.valueOf(verify);
        //存储验证码
        redisService.setStringKeyAndValue(60,phone,integer);
        //打印信息
        log.info("宠物乐园验证码:{},手机号:{}",integer,phone);
    }

    @Override
    @Transactional
    public void register(User user) {
        //验证密码
        if(!StringUtils.equals(user.getPassword(),user.getConfigPassword())){
            throw new BusinessException("2次密码不匹配");
        }
        String code = user.getCode();
        String keyStringValue = redisService.getKeyStringValue(user.getPhone());
        //验证码是否过期
        if(StringUtils.isBlank(keyStringValue)){
            throw new BusinessException("验证吗过期");
        }
        //验证验证码
        if(!StringUtils.equals(code,redisService.getKeyStringValue(user.getPhone()))){
            throw new BusinessException("验证码不匹配");
        }
        //加密
        user.initMD5();
        //插入用户数据
        userMapper.insertSelective(user);

    }

    @Override
    public void emailRegister(User user) {
        String email = user.getEmail();
        boolean matches = Validator.isEmail(email);
        if(!matches){
            throw  new BusinessException("邮箱格式有误");
        }
        //验证邮箱
        List<User> users = userMapper.selectEmail(email);
        if(users.size()>0){
            throw  new BusinessException("邮箱已经注册");
        }
        //验证密码
        if(!StringUtils.equals(user.getPassword(),user.getConfigPassword())){
            throw new BusinessException("2次密码不匹配");
        }
        //加密
        user.initMD5();
        //插入用户数据
        userMapper.insertSelective(user);
    }

    @Override
    public JsonResult frontVerify(LoginDo loginDo) {
        //查用户
        String username = loginDo.getUsername();
        User dbUser = userMapper.selectUsername(username);

        //比对用户
        Optional.ofNullable(dbUser).orElseThrow(() -> new BusinessException("用户名不存在"));
        //准备比对密码
        //获取老盐
        String salt = dbUser.getSalt();
        //对前端密码加密
        String pwd = MD5.create().setSalt(salt.getBytes()).digestHex(loginDo.getPassword());
        log.info("密码:{}",pwd);
        if(!StringUtils.equals(pwd,dbUser.getPassword())){
            throw new BusinessException("用户或者密码错误");
        }
        //准备春token
        String token = IdUtil.fastSimpleUUID();
        //存储数据

        LoginInfo loginInfo = BeanUtil.copyProperties(dbUser, LoginInfo.class);
        //设置用户id
        loginInfo.setUserId(dbUser.getId());
        redisService.setStringKeyAndValue(token,loginInfo,30);
        LoginVo loginVo = BeanUtil.copyProperties(dbUser, LoginVo.class);
        loginVo.setToken(token);
        //存公共的logininfo


        return JsonResult.createSuccess(loginVo);
    }
}
